<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 测试页面</title>
    <script src="/socket.io/socket.io.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, textarea, select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #007AFF;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .messages {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            background-color: #f9f9f9;
            margin-top: 10px;
        }
        .message {
            margin-bottom: 8px;
            padding: 8px;
            border-radius: 4px;
        }
        .message.system {
            background-color: #e3f2fd;
            border-left: 4px solid #2196f3;
        }
        .message.received {
            background-color: #f3e5f5;
            border-left: 4px solid #9c27b0;
        }
        .message.sent {
            background-color: #e8f5e8;
            border-left: 4px solid #4caf50;
        }
        .message.error {
            background-color: #ffebee;
            border-left: 4px solid #f44336;
        }
        .online-users {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            padding: 10px;
            border-radius: 4px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Socket.IO 实时通讯测试</h1>
        
        <!-- 连接控制 -->
        <div class="form-group">
            <label for="userId">用户ID:</label>
            <input type="text" id="userId" placeholder="输入您的用户ID">
            <button onclick="connect()" id="connectBtn">连接</button>
            <button onclick="disconnect()" id="disconnectBtn" disabled>断开连接</button>
        </div>

        <!-- 连接状态 -->
        <div id="status" class="status disconnected">
            未连接
        </div>

        <!-- 在线用户 -->
        <div id="onlineUsers" class="online-users" style="display: none;">
            <strong>在线用户:</strong> <span id="userList"></span>
        </div>

        <!-- 消息发送 -->
        <div class="form-group">
            <label for="messageType">消息类型:</label>
            <select id="messageType">
                <option value="chat">私聊消息</option>
                <option value="broadcast">广播消息</option>
            </select>
        </div>

        <div class="form-group">
            <label for="recipient">接收者 (私聊时填写):</label>
            <input type="text" id="recipient" placeholder="接收者用户ID">
        </div>

        <div class="form-group">
            <label for="messageContent">消息内容:</label>
            <textarea id="messageContent" rows="3" placeholder="输入消息内容"></textarea>
            <button onclick="sendMessage()" id="sendBtn" disabled>发送消息</button>
        </div>

        <!-- 消息显示 -->
        <div class="messages" id="messages"></div>
    </div>

    <script>
        let socket = null;
        let currentUserId = '';

        function connect() {
            const userId = document.getElementById('userId').value.trim();
            if (!userId) {
                alert('请输入用户ID');
                return;
            }

            currentUserId = userId;
            
            // 使用Socket.IO连接
            socket = io({
                transports: ['websocket', 'polling'],
                rejectUnauthorized: false
            });

            socket.on('connect', function() {
                updateStatus('已连接', true);
                document.getElementById('connectBtn').disabled = true;
                document.getElementById('disconnectBtn').disabled = false;
                document.getElementById('sendBtn').disabled = false;
                addMessage('系统', '连接成功！', 'system');
                
                // 登录
                socket.emit('login', { id: userId });
            });

            socket.on('login-success', function(data) {
                addMessage('系统', `登录成功: ${data.id}`, 'system');
            });

            socket.on('login-fail', function(msg) {
                addMessage('错误', `登录失败: ${msg}`, 'error');
            });

            socket.on('new-message', function(data) {
                addMessage(data.from, data.message, 'received');
            });

            socket.on('disconnect', function() {
                updateStatus('连接已断开', false);
                document.getElementById('connectBtn').disabled = false;
                document.getElementById('disconnectBtn').disabled = true;
                document.getElementById('sendBtn').disabled = true;
                document.getElementById('onlineUsers').style.display = 'none';
                addMessage('系统', '连接已断开', 'system');
            });

            socket.on('connect_error', function(error) {
                addMessage('错误', '连接错误: ' + error, 'error');
            });
        }

        function disconnect() {
            if (socket) {
                socket.disconnect();
            }
        }

        function sendMessage() {
            if (!socket || !socket.connected) {
                alert('未连接到服务器');
                return;
            }

            const content = document.getElementById('messageContent').value.trim();
            const type = document.getElementById('messageType').value;
            const recipient = document.getElementById('recipient').value.trim();

            if (!content) {
                alert('请输入消息内容');
                return;
            }

            if (type === 'chat') {
                if (!recipient) {
                    alert('私聊消息需要指定接收者');
                    return;
                }
                
                // 使用HTTP API发送消息（会自动触发WebSocket推送）
                fetch('/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        from: currentUserId,
                        to: recipient,
                        message: content
                    })
                }).then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        // 不立即显示，等待WebSocket推送
                        document.getElementById('messageContent').value = '';
                    } else {
                        addMessage('错误', '发送失败: ' + data.msg, 'error');
                    }
                }).catch(error => {
                    addMessage('错误', '发送失败: ' + error, 'error');
                });
            } else {
                // 广播消息
                socket.emit('broadcast', {
                    from: currentUserId,
                    content: content
                });
                addMessage('我 (广播)', content, 'sent');
                document.getElementById('messageContent').value = '';
            }
        }

        function addMessage(sender, content, type) {
            const messagesDiv = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            messageDiv.innerHTML = `<strong>${sender}:</strong> ${content}`;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        function updateStatus(text, connected) {
            const statusDiv = document.getElementById('status');
            statusDiv.textContent = text;
            statusDiv.className = `status ${connected ? 'connected' : 'disconnected'}`;
        }

        function updateOnlineUsers(users) {
            const userListSpan = document.getElementById('userList');
            const onlineUsersDiv = document.getElementById('onlineUsers');
            
            if (users && users.length > 0) {
                userListSpan.textContent = users.join(', ');
                onlineUsersDiv.style.display = 'block';
            } else {
                onlineUsersDiv.style.display = 'none';
            }
        }

        // 回车发送消息
        document.getElementById('messageContent').addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // 回车连接
        document.getElementById('userId').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                connect();
            }
        });
    </script>
</body>
</html> 